﻿using System;
using System.Collections.Generic ;
using System.Data;
using System.Linq;
using LayerData.DataBaseManager;
using LayerEntity.Almacen;
using Npgsql;
using LayerEntity.Sistema;

namespace LayerData.Almacen
{
    public class DAlmacen
    {
        #region Variables
        readonly string mensajeExecuteReader = "Error al Recuperar #replace, revise lo Siguiente: ";
        readonly IPostgreSqlConnectionInfo connectionInfo;
        public IPostgreSqlConnectionInfo CurrentConection { get; set; }
        #endregion
        #region Contructores
        public DAlmacen()
        {
            this.connectionInfo = ObjectFactory.CreateConnectionInfo();
        }

        public DAlmacen(IPostgreSqlConnectionInfo con)
        {
            this.connectionInfo = con;
            this.CurrentConection = con;
        }

        #endregion

        #region METODOS MANTENIMIENTOS
        public string MantenimientoAlamacenes(EAlmacen almacen, EnumOperaciones operacion)
        {
            String proc = "";
            String msg = "";
            bool res = false;
            NpgsqlConnection con = null;
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                NpgsqlTransaction tran = this.CurrentConection.GetTransaction(con);
                proc = (string)PostgreSqlHelper.ExecuteScalar(this.CurrentConection, tran, "almacen.isp_grabar_almacen", almacen.ToObject((int)operacion));
                if (proc == "0")
                {
                    Console.Write(string.Format("--- TRANZACCION HACEPTADA {0}", msg));
                    res = true;
                }
                else
                {
                    if (proc == "-1")
                    {
                        res = false;
                        this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                    }
                    else
                    {
                        if (proc == "-2")
                        {
                            res = false;
                            this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                        }
                        else
                        {
                            if (proc == "-3")
                            {
                                res = false;
                                this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                            }
                            else
                            {
                                if (proc == "-4")
                                {
                                    res = false;
                                    this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                                }
                                else
                                {
                                    res = false;
                                    this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                                }
                            }
                        }
                    }
                }
                if (res == true)
                {
                    this.CurrentConection.CommintTransaction(tran);
                }
            }
            catch (NpgsqlException ex)
            {
                Console.Write(ex.Message);
                this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                proc = ex.Message;
                throw;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return proc;
        }
        public string[] MantenimientoInventarios(EInventario inv, EnumOperaciones operacion)
        {
            bool res = false;
            NpgsqlConnection con = null;
            string[] result = null;
            object obj;
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                NpgsqlTransaction tran = this.CurrentConection.GetTransaction(con);
                obj = PostgreSqlHelper.ExecuteScalar(this.CurrentConection, tran, "almacen.ISP_GRBAR_INVENTARIO", inv.toSaveInventario((int)operacion));

                if (obj != null)
                {
                    result = (string[])obj;
                }
                else
                {

                    result = new string[] { "I-00" };
                }
                if (result[0] == "0")
                {
                    res = true;
                }
                else
                {
                    res = false;
                    this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                    
                }
                if (res == true)
                {
                    this.CurrentConection.CommintTransaction(tran);
                }
            }
            catch (NpgsqlException ex)
            {
                Console.Write(ex.Message);
                result = new string[] { ex.Message };
                this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                throw;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return result;
        }
        public string[] MantenimientoDetInventarios(EDetInventory inv,ESeriesProd Eser, EnumOperaciones operacion)
        {
            bool res = false;
            NpgsqlConnection con = null;
            string[] result = null;
            string[] getPkInv = null;
            object obj;
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                NpgsqlTransaction tran = this.CurrentConection.GetTransaction(con);
                obj = PostgreSqlHelper.ExecuteScalar(this.CurrentConection, tran, "almacen.ISP_SAVE_DET_INVENTORY", inv.toSaveDetInventory((int)operacion));

                if (obj != null)
                {
                    result = (string[])obj;
                    getPkInv = (string[])obj;
                }
                else
                {

                    result = new string[] { "ID-00" };
                }
                if (result[0] == "0")
                {
                    if (Eser.Series.Rows.Count > 0)// SI EL PRODUCTO MANEGA SERIES 
                    {
                        foreach (DataRow dr in Eser.Series.Rows)
                        {
                            ESeriesProd objEser = new ESeriesProd();
                            objEser.Id_Serie = dr["Nro_Motor"].ToString();
                            objEser.Id_Usuario = "";
                            objEser.Nro_Chasis = dr["Nro_Chasis"].ToString();
                            objEser.Nro_Motor = dr["Nro_Motor"].ToString();
                            objEser.Anio_Fabrica = dr["Anio_Fabrica"].ToString();
                            objEser.Anio_Modelo = dr["Anio_Modelo"].ToString();
                            objEser.Id_Unimed = inv.Id_unidad;
                            objEser.Id_Poroducto = inv.Id_producto;
                            objEser.Id_Estado = Eser.Id_Estado;
                            obj = PostgreSqlHelper.ExecuteScalar(this.CurrentConection, tran, "almacen.ISP_GRABAR_SERIES", Eser.toSaveSeries((int)operacion, objEser));
                            if (obj != null)
                            {
                                result = (string[])obj;
                            }
                            else
                            {

                                result = new string[] { "S-00" };
                            }
                            if (result[0] == "0")
                            {
                                ESeriesProd EserInv = new ESeriesProd();
                                EInventario InvSer = new EInventario();
                                EserInv.Id_Serie = result[1];
                                InvSer.Fecha = inv.Fecha;
                                EserInv.Id_Estado = Eser.Id_Estado;
                                InvSer.Id_almacen = inv.Id_almacen;
                                EserInv.Id_Usuario = Eser.Id_Usuario;
                                InvSer.Id_documento = inv.Id_documento;
                                InvSer.Serie = inv.Serie;
                                InvSer.Nro_inventario = inv.Nro_inventario;
                                obj = PostgreSqlHelper.ExecuteScalar(this.CurrentConection, tran, "almacen.ISP_GRABAR_SERIEPROD_INV", Eser.toSaveSeriesInventory((int)operacion, EserInv, InvSer));
                                if (obj != null)
                                {
                                    result = (string[])obj;
                                }
                                else
                                {

                                    result = new string[] { "DIS-00" };
                                }
                                if (result[0] == "0")
                                {
                                    res = true;
                                }
                                else
                                {
                                    this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                                    res = false;
                                    break;
                                }
                                //res = true;
                            }
                            else
                            {
                                this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                                res = false;
                                break;
                            }

                        }
                    }
                    else
                    {
                        res = true;
                        ///OCURRE CUANDO EL PRODUCTO NO MANEJA NINGUNA SERIE
                    }



                    //////////////////////**************
                    //res = true;
                }
                else
                {
                    res = false;
                    this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());

                }
                if (res == true)
                {
                    this.CurrentConection.CommintTransaction(tran);
                }
            }
            catch (NpgsqlException ex)
            {
                Console.Write(ex.Message);
                result = new string[] { ex.Message };
                this.CurrentConection.CancelarConexionTrans(this.CurrentConection.GetPostgreSqlConnection());
                throw;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return result;
        }
        #endregion
        #region LISTADO

        public DataTable GetListaAlamcen(EAlmacen obj)
        {
            DataTable dtb;
            NpgsqlConnection con = null;

            AccesoBD db = new AccesoBD();
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                dtb = db.EjecutaModelView("almacen.v_listar_almacen", new object[] { obj.Condicion }, con);
            }
            catch (NpgsqlException ex)
            {
                this.CurrentConection.CloseConnection(con);
                Console.Write(string.Format("{0}/{1}", ex.Message, ex.Source));
                DataBaseUtils.PrintMessajeError(this.mensajeExecuteReader.Replace("#replace", " Los Productos"), ex);
                return null;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return dtb;
        }

         

        public DataTable GetListaStockAlamcen(EAlmacen obj)
        {
            DataTable dtb;
            NpgsqlConnection con = null;

            AccesoBD db = new AccesoBD();
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                dtb = db.EjecutaModelView("almacen.V_LISTAR_STOK_ALMACEN", new object[] { obj.Condicion }, con);
            }
            catch (NpgsqlException ex)
            {
                this.CurrentConection.CloseConnection(con);
                DataBaseUtils.PrintMessajeError(this.mensajeExecuteReader.Replace("#replace", " Los Productos"), ex);
                return null;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return dtb;
        }
        public DataTable GetListaCabInventario(ESistema obj)
        {
            DataTable dtb;
            NpgsqlConnection con = null;

            AccesoBD db = new AccesoBD();
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                dtb = db.EjecutaModelView("almacen.v_listar_cab_inventario", new object[] { obj.Condicion }, con);
            }
            catch (NpgsqlException ex)
            {
                this.CurrentConection.CloseConnection(con);
                DataBaseUtils.PrintMessajeError(this.mensajeExecuteReader.Replace("#replace", " Los Productos"), ex);
                return null;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return dtb;
        }

        public DataTable GetListaDetInventario(ESistema obj)
        {
            DataTable dtb;
            NpgsqlConnection con = null;

            AccesoBD db = new AccesoBD();
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                dtb = db.EjecutaModelView("almacen.v_listar_det_inventario", new object[] { obj.Condicion }, con);
            }
            catch (NpgsqlException ex)
            {
                this.CurrentConection.CloseConnection(con);
                DataBaseUtils.PrintMessajeError(this.mensajeExecuteReader.Replace("#replace", " Los Productos"), ex);
                return null;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return dtb;
        }
        public DataTable GetListaSeriesProducts(ESistema obj)
        {
            DataTable dtb;
            NpgsqlConnection con = null;

            AccesoBD db = new AccesoBD();
            try
            {
                con = this.CurrentConection.GetPostgreSqlConnection();
                dtb = db.EjecutaModelView("almacen.v_listar_series_prod", new object[] { obj.Condicion }, con);
            }
            catch (NpgsqlException ex)
            {
                this.CurrentConection.CloseConnection(con);
                DataBaseUtils.PrintMessajeError(this.mensajeExecuteReader.Replace("#replace", " Las series"), ex);
                return null;
            }
            finally
            {
                this.CurrentConection.CloseConnection(con);
            }
            return dtb;
        }
        #endregion

        #region Funciones de Listado List<T>
        public List<EAlmacen> GetAlmacen() {
            List<EAlmacen> list = new List<EAlmacen>();
            NpgsqlConnection con = CurrentConection.GetPostgreSqlConnection();
            try
            {
                CurrentConection.OpenConnection(con);
                NpgsqlDataReader dr = PostgreSqlHelper.ExecuteReader(CurrentConection, CommandType.Text, "SELECT * FROM almacen.tb_almacen;");
                if (dr.HasRows) {
                    while (dr.Read()) { 
                    list.Add (new EAlmacen (dr));
                    }
                }
            }
            catch (Exception ex)
            {
                DataBaseUtils.PrintMessajeError("", ex);
            }
            finally {
                CurrentConection.CloseConnection(con);
            }


            return list;
        }
        #endregion
    }
}